<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="icon" href="/assets/logo.png?v=2.0.0" type="image/png" sizes="16x16"><link rel="icon" href="/assets/logo.png?v=2.0.0" type="image/png" sizes="32x32"><meta name="description" content="由于平时写代码和博客常常用到git和github，每次用到都去百度，感觉太麻烦了，也大大降低了效率，索性自己整理一下常用到的git指令和使用方法，对git的使用能有一个系统的认识。这里只介绍一下基本用法，对更高级的用法如果以后用到再进行补充。">
<meta property="og:type" content="article">
<meta property="og:title" content="git基本使用方法">
<meta property="og:url" content="https://wxler.gitee.io/2020/06/17/gitUseMethod/index.html">
<meta property="og:site_name" content="Lei&#39;s Blog">
<meta property="og:description" content="由于平时写代码和博客常常用到git和github，每次用到都去百度，感觉太麻烦了，也大大降低了效率，索性自己整理一下常用到的git指令和使用方法，对git的使用能有一个系统的认识。这里只介绍一下基本用法，对更高级的用法如果以后用到再进行补充。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-22.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-21.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-24.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-25.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-26.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-27.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-30.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-29.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-31.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-32.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-36.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-37.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-33.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-34.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-35.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-39.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-38.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-40.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-41.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-42.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-43.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-44.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-45.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-46.png">
<meta property="og:image" content="https://wxler.gitee.io/images/pasted-47.png">
<meta property="article:published_time" content="2020-06-17T03:59:00.000Z">
<meta property="article:modified_time" content="2020-07-16T01:07:21.172Z">
<meta property="article:author" content="wxl">
<meta property="article:tag" content="git">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wxler.gitee.io/images/pasted-22.png"><meta name="keywords" content="wxl, Lei's Blog"><meta name="description" content="博客，分享，开源，心得"><title>git基本使用方法 | Lei's Blog</title><link ref="canonical" href="https://wxler.gitee.io/2020/06/17/gitUseMethod/"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.12.1/css/all.min.css" type="text/css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js@1.0.16/dist/css/share.min.css" type="text/css"><link rel="stylesheet" href="/css/index.css?v=2.0.0"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement('script');
  hm.src = 'https://hm.baidu.com/hm.js?01911aa0fc6bdb840626994292397110';
  hm.async = true;

  if (true) {
    hm.setAttribute('data-pjax', '');
  }
  var s = document.getElementsByTagName('script')[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><script>var Stun = window.Stun || {};
var CONFIG = {
  root: '/',
  algolia: undefined,
  fontIcon: {"prompt":{"success":"fas fa-check-circle","info":"fas fa-arrow-circle-right","warning":"fas fa-exclamation-circle","error":"fas fa-times-circle"},"copyBtn":"fas fa-copy"},
  sidebar: {"offsetTop":"20px","tocMaxDepth":6},
  header: {"enable":true,"showOnPost":true,"scrollDownIcon":true},
  postWidget: {"endText":true},
  nightMode: {"enable":true},
  back2top: {"enable":true},
  codeblock: {"style":"default","highlight":"ocean","wordWrap":false},
  reward: false,
  fancybox: false,
  zoomImage: {"gapAside":"20px"},
  galleryWaterfall: undefined,
  lazyload: true,
  pjax: {"avoidBanner":true},
  externalLink: {"icon":{"enable":true,"name":"fas fa-external-link-alt"}},
  shortcuts: undefined,
  prompt: {"copyButton":"复制","copySuccess":"复制成功","copyError":"复制失败"},
  sourcePath: {"js":"js","css":"css","images":"images"},
};

window.CONFIG = CONFIG;</script><meta name="generator" content="Hexo 4.2.1"></head><body><div class="container" id="container"><header class="header" id="header"><div class="header-inner"><nav class="header-nav header-nav--fixed"><div class="header-nav-inner"><div class="header-nav-menubtn"><i class="fas fa-bars"></i></div><div class="header-nav-menu"><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/"><span class="header-nav-menu-item__icon"><i class="fas fa-home"></i></span><span class="header-nav-menu-item__text">首页</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/archives/"><span class="header-nav-menu-item__icon"><i class="fas fa-folder-open"></i></span><span class="header-nav-menu-item__text">归档</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/categories/"><span class="header-nav-menu-item__icon"><i class="fas fa-layer-group"></i></span><span class="header-nav-menu-item__text">分类</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/tags/"><span class="header-nav-menu-item__icon"><i class="fas fa-tags"></i></span><span class="header-nav-menu-item__text">标签</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/message/"><span class="header-nav-menu-item__icon"><i class="fa fa-comment"></i></span><span class="header-nav-menu-item__text">留言板</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/about/"><span class="header-nav-menu-item__icon"><i class="fas fa-user"></i></span><span class="header-nav-menu-item__text">关于</span></a></div></div><div class="header-nav-search"><span class="header-nav-search__icon"><i class="fas fa-search"></i></span><span class="header-nav-search__text">搜索</span></div><div class="header-nav-mode"><div class="mode"><div class="mode-track"><span class="mode-track-moon"></span><span class="mode-track-sun"></span></div><div class="mode-thumb"></div></div></div></div></nav><div class="header-banner"><div class="header-banner-info"><div class="header-banner-info__title">Lei's Blog</div><div class="header-banner-info__subtitle">一个爱好coding的男孩纸</div></div><div class="header-banner-arrow"><div class="header-banner-arrow__icon"><i class="fas fa-angle-down"></i></div></div></div></div></header><main class="main" id="main"><div class="main-inner"><div class="content-wrap" id="content-wrap"><div class="content" id="content"><!-- Just used to judge whether it is an article page--><div id="is-post"></div><div class="post"><header class="post-header"><h1 class="post-title">git基本使用方法</h1><div class="post-meta"><span class="post-meta-item post-meta-item--createtime"><span class="post-meta-item__icon"><i class="far fa-calendar-plus"></i></span><span class="post-meta-item__info">发表于</span><span class="post-meta-item__value">2020-06-17</span></span><span class="post-meta-item post-meta-item--updatetime"><span class="post-meta-item__icon"><i class="far fa-calendar-check"></i></span><span class="post-meta-item__info">更新于</span><span class="post-meta-item__value">2020-07-16</span></span><span class="post-meta-item post-meta-item--wordcount"><span class="post-meta-item__icon"><i class="far fa-file-word"></i></span><span class="post-meta-item__info">字数统计</span><span class="post-meta-item__value">3.5k</span></span><span class="post-meta-item post-meta-item--readtime"><span class="post-meta-item__icon"><i class="far fa-clock"></i></span><span class="post-meta-item__info">阅读时长</span><span class="post-meta-item__value">20分</span></span></div></header><div class="post-body"><p>由于平时写代码和博客常常用到git和github，每次用到都去百度，感觉太麻烦了，也大大降低了效率，索性自己整理一下常用到的git指令和使用方法，对git的使用能有一个系统的认识。这里只介绍一下基本用法，对更高级的用法如果以后用到再进行补充。</p>
<a id="more"></a>

        <h2 id="git安装和配置"   >
          <a href="#git安装和配置" class="heading-link"><i class="fas fa-link"></i></a>git安装和配置</h2>
      
<p>git的安装和配置在我的这篇<span class="exturl"><a class="exturl__link"   href="https://wxler.github.io/2020/06/01/hexoCreateAndConfig/#%E5%AE%89%E8%A3%85git"  target="_blank" rel="noopener">搭建个人博客</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span>里，请自行参考配置，主要有一下几点：</p>
<ul>
<li>下载安装git程序</li>
<li>配置github账户</li>
<li>配置SSH KEY</li>
</ul>

        <h2 id="git工作原理"   >
          <a href="#git工作原理" class="heading-link"><i class="fas fa-link"></i></a>git工作原理</h2>
      
<p>Git是分布式版本控制系统，那么它就没有中央服务器的，每个人的电脑就是一个完整的版本库，这样，工作的时候就不需要联网了，因为版本都是在自己的电脑上。既然每个人的电脑都有一个完整的版本库，那多个人如何协作呢？比如说自己在电脑上改了文件A，其他人也在电脑上改了文件A，这时，你们两之间只需把各自的修改推送给对方，就可以互相看到对方的修改了。Git在执行更新操作时，更像是对数据的一组快照，每次你提交更新，它主要对当时的全部文件制作一个快照并保存这个快照的索引。为了高效，如果文件没有修改，Git不再重新存储该文件，而是只保留一个链接指向之前存储的文件。<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-22.png"  alt="upload successful" />
      <br />
如上图所示，在version2中的B即是因为File B没有改变，所以直接存储了一个指向FileB的链接。只有修改了的文件才会产生一个新的文件，覆盖原来的文件。<br />
git的工作原理/流程如下:<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-21.png"  alt="upload successful" />
      </p>
<ul>
<li>Workspace：工作区(本地目录文件)</li>
<li>Index / Stage：暂存区/缓存区</li>
<li>Repository：仓库区（或本地仓库）</li>
<li>Remote：远程仓库</li>
</ul>

        <h2 id="基本操作"   >
          <a href="#基本操作" class="heading-link"><i class="fas fa-link"></i></a>基本操作</h2>
      

        <h3 id="初始化仓库"   >
          <a href="#初始化仓库" class="heading-link"><i class="fas fa-link"></i></a>初始化仓库</h3>
      
<p>仓库的初始化有两种方式：一种是直接从远程仓库克隆，另一种则是直接从当前目录初始化。远程初始化命令在<a href="#%E4%BB%8E%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E8%8E%B7%E5%8F%96">从远程仓库获取</a>，本地初始化命令的方法是首先创建一个文件夹，我命名为mygit，然后执行如下命令：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git init</span><br></pre></td></tr></table></div></figure>
<p>执行完毕后，当前目录下会出现一个隐藏的.git文件夹，git所需的数据和资源都放在改目录中。</p>

        <h3 id="查看仓库状态"   >
          <a href="#查看仓库状态" class="heading-link"><i class="fas fa-link"></i></a>查看仓库状态</h3>
      
<p>通过<code>git status</code>来查看仓库状态，执行效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-24.png"  alt="upload successful" />
      <br />
可以看到nothing to commit，表示本地工作区没有要提交的文件，我们再创建一个one.txt的文件，然后在执行<code>git status</code>，效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-25.png"  alt="upload successful" />
      <br />
从结果Untracked files可以看到，one.txt还没有被add到暂存区。</p>

        <h3 id="添加文件到暂存区"   >
          <a href="#添加文件到暂存区" class="heading-link"><i class="fas fa-link"></i></a>添加文件到暂存区</h3>
      
<p><code>git add</code>命令可以将一个文件添加到暂存区,执行如下命令将one.txt添加到暂存区：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">git add one.txt</span><br></pre></td></tr></table></div></figure>
<p>将one.txt添加到暂存区后，再次执行<code>git status</code>,可看到如下效果：  
        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-26.png"  alt="upload successful" />
      <br />
从Changes to be committed可以看出，one.txt已被添加到暂存区，但还未被添加到本地仓库。</p>

        <h3 id="提交到本地仓库"   >
          <a href="#提交到本地仓库" class="heading-link"><i class="fas fa-link"></i></a>提交到本地仓库</h3>
      
<p>当文件提交到暂存区之后，执行<code>git commit</code>命令将当前暂存区的文件提交到本地仓库，执行如下命令：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">git commit -m <span class="string">'新增一个one.txt'</span></span><br></pre></td></tr></table></div></figure>
<p>-m是指将当前暂存区的文件提交到本地仓库的时候，加上提交备注/说明，再次执行<code>git status</code>,可以看到已经没有要add或commit的文件了。这里要强调一下，如果直接执行<code>git commit</code>命令，会自动打开一个vi编辑器，在里面输入备注/说明即可。此外，当我们提交成功后，还可以通过<code>git commit --amend</code>修改备注信息。</p>

        <h3 id="查看更改前后的差异"   >
          <a href="#查看更改前后的差异" class="heading-link"><i class="fas fa-link"></i></a>查看更改前后的差异</h3>
      
<p>使用<code>git diff</code>命令可以查看<strong>工作区和暂存区的区别</strong>，在one.txt里面写入一行hello world，然后执行<code>git diff</code>命令，结果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-27.png"  alt="upload successful" />
      <br />
根据结果可以看到新增了一行hello world，如果我们要比较<strong>工作区与最新本地版本库的区别</strong>，可以执行<code>git diff HEAD</code>，结果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-30.png"  alt="upload successful" />
      </p>

        <h3 id="查看提交历史"   >
          <a href="#查看提交历史" class="heading-link"><i class="fas fa-link"></i></a>查看提交历史</h3>
      
<p>使用<code>git log</code>查看提交历史，我们首先将工作区的内容提交到本地仓库，执行<code>git add one.txt</code>将更改后的one.txt添加到暂存区，执行<code>git commit -m '添加了一行hello world'</code>将暂存区的内容提交到本地仓库，然后执行<code>git log</code>，结果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-29.png"  alt="upload successful" />
      </p>

        <h2 id="git撤销修改"   >
          <a href="#git撤销修改" class="heading-link"><i class="fas fa-link"></i></a>git撤销修改</h2>
      

        <h3 id="工作区的代码撤销"   >
          <a href="#工作区的代码撤销" class="heading-link"><i class="fas fa-link"></i></a>工作区的代码撤销</h3>
      
<p>使用<code>git checkout</code>撤销工作区的代码。我们先向one.txt添加一行hello everyone，执行<code>cat one.txt</code>查看内容，再执行<code>git checkout -- one.txt</code>撤销之前的操作，让one,txt恢复之前的状态，然后执行<code>cat one.txt</code>再次查看内容，效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-31.png"  alt="upload successful" />
      <br />
可以看到，工作区的内容已经被修改,这时候本地文件刚刚添加的内容就被撤销了。</p>

        <h3 id="暂存区的代码撤销"   >
          <a href="#暂存区的代码撤销" class="heading-link"><i class="fas fa-link"></i></a>暂存区的代码撤销</h3>
      
<p>使用<code>git reset HEAD</code>撤销暂存区的代码。首先在one.txt添加一行hello people，执行<code>git add one.txt</code>将更改的内容提交到暂存区，<code>git reset HEAD</code>来撤销暂存区的代码，如下图：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-32.png"  alt="upload successful" />
      <br />
撤销暂存区的代码之后，如需要将代码添加到暂存区，则需要再次执行<code>git add</code>命令</p>

        <h3 id="本地仓库的代码撤销"   >
          <a href="#本地仓库的代码撤销" class="heading-link"><i class="fas fa-link"></i></a>本地仓库的代码撤销</h3>
      
<p>可以使用<code>git reset --hard &lt;版本号&gt;</code>来撤销本地仓库的代码，版本号有几种不同的写法：</p>
<ol>
<li>可以使用HEAD<sup>来描述版本，一个</sup>表示前一个版本，两个^^表示前两个版本，以此类推。</li>
<li>也可以使用数字来代替^，比如说前100个版本可以写作HEAD~100。</li>
<li>也可以直接写版本号，表示跳转到某一个版本处。我们每次提交成功后，都会生成一个哈希码作为版本号，所以这里我们也可以直接填版本号，哈希码很长，但是我们不用全部输入，只需要输入前面几个字符即可，就能识别出来。执行<code>git log</code>后那一串长符号就是哈希码版本号。</li>
</ol>
<p>依次执行如下命令：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ git add <span class="string">'one.txt'</span></span><br><span class="line">$ git commit -m <span class="string">'添加一行hello people'</span></span><br><span class="line">$ git reset --hard head^</span><br></pre></td></tr></table></div></figure>
<p>执行<code>git reset --hard head^</code>后的效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-36.png"  alt="upload successful" />
      <br />
可以从结果看出，前半部分816b208是执行撤销操作以后，当前版本的版本号前七位，后半部分是该版本的备注，可以用<code>git log</code>来查看不同版本的版本号和备注。</p>
<p>再次查看本地one.txt文件，发现本地目录的刚刚添加的内容已经没有了，如需要再次提交到本地仓库，则可执行<code>git add</code>和<code>git commit</code>命令。<strong>需要注意的是，当撤销到最开始版本的时候，<code>git reset --hard head^</code>就不能再用了，否则会报如下的错误：</strong><br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-37.png"  alt="upload successful" />
      </p>

        <h2 id="git分支管理"   >
          <a href="#git分支管理" class="heading-link"><i class="fas fa-link"></i></a>git分支管理</h2>
      

        <h3 id="查看分支"   >
          <a href="#查看分支" class="heading-link"><i class="fas fa-link"></i></a>查看分支</h3>
      
<p>通过<code>git branch</code>来查看当前仓库有哪些分支和我们处于哪一分支中，如下所示：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-33.png"  alt="upload successful" />
      <br />
可以看到，当前本地仓库只有一个master分支，这是git默认创建出来的，master前面的*表示我们当前处于这一个分支中。</p>

        <h3 id="分支创建和切换"   >
          <a href="#分支创建和切换" class="heading-link"><i class="fas fa-link"></i></a>分支创建和切换</h3>
      
<p>可以利用<code>git branch &lt;分支名&gt;</code>来创建一个分支，利用<code>git checkout &lt;分支名&gt;</code>来切换分支，如下所示：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-34.png"  alt="upload successful" />
      </p>

        <h3 id="分支合并"   >
          <a href="#分支合并" class="heading-link"><i class="fas fa-link"></i></a>分支合并</h3>
      
<p>由于math分支是从master分支中创建出来的，所以此时math分支的内容和master分支的内容是一致的，现在，我们在math分支向one.txt添加一行hello branch math(由于刚刚执行了<a href="#%E6%9C%AC%E5%9C%B0%E4%BB%93%E5%BA%93%E7%9A%84%E4%BB%A3%E7%A0%81%E6%92%A4%E9%94%80">本地仓库的代码撤销</a>，所以one.txt现在的内容是空白的)，此时math分支的one.txt和math分支的one.txt就不同了，具体效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-35.png"  alt="upload successful" />
      <br />
执行完毕后，我们也可以在本地查看，先在math分支下，打开one.txt可以看到我们刚刚添加的内容，然后再切换到master分支，再从本地打开one.txt文件，就看不到内容了。<br />
<strong>可以通过<code>git merge &lt;分支名&gt;</code>合并分支</strong>，先切换到master分支，然后执行<code>git merge math</code>合并math分支到master分支上，效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-39.png"  alt="upload successful" />
      <br />
可以看到再次在master分支下查看one.txt，就可以显示math分支的内容了。</p>
<p>通常合并分支时，git一般使用”Fast forward”模式，fast-forward方式表示当条件允许时，git直接把HEAD指针指向合并分支的头，完成合并，这种方式合并速度快，但是在整个过程中没有创建commit。在这种模式下，删除分支后，会丢掉分支信息，可使用带参数 <code>–no-ff</code>来禁用”Fast forward”模式，即删除时可以实用<code>git merge --no-ff &lt;分支名&gt;</code></p>

        <h3 id="以图表方式查看分支"   >
          <a href="#以图表方式查看分支" class="heading-link"><i class="fas fa-link"></i></a>以图表方式查看分支</h3>
      
<p>可以用<code>git log --graph</code>命令来直观的查看分支的创建和合并等操作，合并math和master分支前的效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-38.png"  alt="upload successful" />
      <br />
合并math和master分支后的效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-40.png"  alt="upload successful" />
      </p>

        <h3 id="解决冲突"   >
          <a href="#解决冲突" class="heading-link"><i class="fas fa-link"></i></a>解决冲突</h3>
      
<p>我们创建一个新的分支dev,并在dev分支下给one.txt添加一行12345，然后提交，如下所示：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-41.png"  alt="upload successful" />
      <br />
同样，我们现在切换到master分支上来，也在one.txt添加一行内容，内容为56789，并提交，如下所示：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-42.png"  alt="upload successful" />
      <br />
现在，我们将dev分支合并到master上来，如下所示：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-43.png"  alt="upload successful" />
      <br />
从结果中可以看出，=======之前是主分支的内容，=======之后是dev分支的内容，此时我们用文本编辑器修改one.txt的冲突然后提交即可，如下所示：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-44.png"  alt="upload successful" />
      </p>
<p><strong>分支策略：首先master主分支应该是非常稳定的，也就是用来发布新版本，一般情况下不允许在上面干活，干活一般情况下在新建的dev分支上干活，干完后，dev分支代码可以合并到主分支master上来。</strong></p>

        <h2 id="github远程仓库"   >
          <a href="#github远程仓库" class="heading-link"><i class="fas fa-link"></i></a>github远程仓库</h2>
      

        <h3 id="关联远程仓库"   >
          <a href="#关联远程仓库" class="heading-link"><i class="fas fa-link"></i></a>关联远程仓库</h3>
      
<p>在此之前我相信你已经配置SSH KEY，如果没有，可以参考我的这篇<a href="https://wxler.gitee.io/2020/06/01/hexoCreateAndConfig/#git%E9%85%8D%E7%BD%AE">搭建个人博客</a>里进行配置，配置完成以后在github上创建一个仓库，这里命名为test，我们可以看到仓库的地址，例如：<code>https://github.com/wxler/test.git</code>。然后将我们之前的本地仓库和这个远程仓库进行关联，使用<code>git remote add</code>命令，如下：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git remote add origin https://github.com/wxler/test.git</span><br></pre></td></tr></table></div></figure>

        <h3 id="推送到远程仓库"   >
          <a href="#推送到远程仓库" class="heading-link"><i class="fas fa-link"></i></a>推送到远程仓库</h3>
      
<p>把本地库的内容推送到远程，使用<code>git push -u origin master</code>命令，实际上是把当前分支master推送到远程。由于远程库是空的，我们第一次推送master分支时，加上了–u参数，Git不但会把本地的master分支内容推送的远程新的master分支，还会把本地的master分支和远程的master分支关联起来，在以后的推送或者拉取时就可以简化命令,不用加-u了,效果如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-45.png"  alt="upload successful" />
      <br />
推送成功后，可以立刻在github页面中看到远程库的内容已经和本地一模一样了。从现在起，只要本地作了提交，就可以通过命令：<code>git push origin master</code>把本地master分支的最新修改推送到github上了，现在你就拥有了真正的分布式版本库了。<br />
**我们一般不把其它分支推送到远程仓库，master主分支是最稳定的版本，一般情况下不允许在上面干活，干活一般情况下在新建的分支上干活，干完后，把分支代码可以合并到主分支master上来。**当然，你也可以将其它分支推送到远程仓库，可以执行如下命令：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ git checkout fa</span><br><span class="line">$ git push -u origin fa</span><br></pre></td></tr></table></div></figure>

        <h3 id="从远程仓库获取"   >
          <a href="#从远程仓库获取" class="heading-link"><i class="fas fa-link"></i></a>从远程仓库获取</h3>
      
<p>我们可以通过git clone命令克隆一个远程仓库到本地,方式也简单，在本地创建一个空文件夹，执行如下命令：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git <span class="built_in">clone</span> https://github.com/wxler/test.git</span><br></pre></td></tr></table></div></figure>
<p>此时克隆的是master分支到本地仓库，我们可以通过<code>git branch -a</code>来查看本地仓库和远程仓库的信息，-a参数可以同时显示本地仓库和远程仓库的信息，如下：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-46.png"  alt="upload successful" />
      <br />
我们也可以把远程仓库其它分支的内容clone下来，可以执行如下命令：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ git branch fa origin/dev</span><br><span class="line">$ git checkout dev</span><br></pre></td></tr></table></div></figure>
<p>上面的指令表示根据远程仓库的dev分支创建一个本地仓库的dev分支，然后再切换到dev分支，<strong>注意由于dev分支就是从远程仓库克隆下来的，所以这里可以不添加-u参数。</strong></p>

        <h3 id="从远程仓库更新"   >
          <a href="#从远程仓库更新" class="heading-link"><i class="fas fa-link"></i></a>从远程仓库更新</h3>
      
<p>使用<code>git pull</code>获取远程仓库最新的代码和数据，例如，我们可以通过以下代码将远程主机的master分支最新内容拉下来后与当前本地分支直接合并</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">git pull origin master</span><br></pre></td></tr></table></div></figure>

        <h2 id="git命令大全"   >
          <a href="#git命令大全" class="heading-link"><i class="fas fa-link"></i></a>git命令大全</h2>
      
<p>git常用命令速查表，方便查阅：<br />

        <img   class="lazyload lazyload-gif"
          src="/images/loading.svg" data-src="/images/pasted-47.png"  alt="upload successful" />
      </p>

        <h2 id="遗留问题"   >
          <a href="#遗留问题" class="heading-link"><i class="fas fa-link"></i></a>遗留问题</h2>
      
<p>到现在，我们就可以使用git的大多数操作了，但是还有git的一些操作平常没有用到，我也就不主动去一个个试了，毕竟一口吃不成胖子，查了也记不住，就不自找苦吃了，遗留的问题主要有：</p>
<ul>
<li>git分支衍合</li>
<li>git标签管理</li>
<li>bug分支&amp;stash功能</li>
</ul>

        <h2 id="参考文档"   >
          <a href="#参考文档" class="heading-link"><i class="fas fa-link"></i></a>参考文档</h2>
      
<p><span class="exturl"><a class="exturl__link"   href="https://mp.weixin.qq.com/s?__biz=MzI1NDY0MTkzNQ==&amp;mid=100004284&amp;idx=1&amp;sn=f9adbded2bac4d8efb9b07a0262a0e8a&amp;chksm=69c343dc5eb4cacaa45d2a968ab935e85eccbcb11f9493d32ef147da5c1a1ff53cc45a1f32a2&amp;mpshare=1&amp;scene=1&amp;srcid=0616SVENp6ameT2V21QsW2nZ&amp;sharer_sharetime=1592289626242&amp;sharer_shareid=18383980e942ee6dfd94ea4b7b61fcbe&amp;key=1de400e48ea73360020a1786d1997d16a5b67307619595df7c6b06fc16be187dba8368d87386b6a57a40d3c3f3671fae6927462285e9b59479eb08a036e5aa45b02add3de42bb86044ef6649218a6531&amp;ascene=1&amp;uin=MjA2Nzc1NzU0Mg%3D%3D&amp;devicetype=Windows+10+x64&amp;version=6209007b&amp;lang=zh_CN&amp;exportkey=ASZhqnZ2JNrU1FCHtEQsA0s%3D&amp;pass_ticket=DNBBiZIg7%2Fjg4GBZz9sSD49h8dYitJv5rAPR21lJbAICH1bIYdByWmp3fQOoDyHW"  target="_blank" rel="noopener">松哥git教程</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span><br />
<span class="exturl"><a class="exturl__link"   href="https://www.jianshu.com/p/34cfe097e06a"  target="_blank" rel="noopener">Git从入门到熟练使用</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span><br />
<span class="exturl"><a class="exturl__link"   href="https://www.cnblogs.com/jjlee/p/10305194.html"  target="_blank" rel="noopener">史上最简单Git入门教程</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span><br />
<span class="exturl"><a class="exturl__link"   href="https://www.jianshu.com/p/46ffff059092"  target="_blank" rel="noopener">git命令大全</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span></p>
<blockquote>
<p>特别声明：本篇博客只做个人学习交流和参考手册使用，不作任何商业目的，内容上较多参考了<span class="exturl"><a class="exturl__link"   href="https://mp.weixin.qq.com/s?__biz=MzI1NDY0MTkzNQ==&amp;mid=100004284&amp;idx=1&amp;sn=f9adbded2bac4d8efb9b07a0262a0e8a&amp;chksm=69c343dc5eb4cacaa45d2a968ab935e85eccbcb11f9493d32ef147da5c1a1ff53cc45a1f32a2&amp;mpshare=1&amp;scene=1&amp;srcid=0616SVENp6ameT2V21QsW2nZ&amp;sharer_sharetime=1592289626242&amp;sharer_shareid=18383980e942ee6dfd94ea4b7b61fcbe&amp;key=1de400e48ea73360020a1786d1997d16a5b67307619595df7c6b06fc16be187dba8368d87386b6a57a40d3c3f3671fae6927462285e9b59479eb08a036e5aa45b02add3de42bb86044ef6649218a6531&amp;ascene=1&amp;uin=MjA2Nzc1NzU0Mg%3D%3D&amp;devicetype=Windows+10+x64&amp;version=6209007b&amp;lang=zh_CN&amp;exportkey=ASZhqnZ2JNrU1FCHtEQsA0s%3D&amp;pass_ticket=DNBBiZIg7%2Fjg4GBZz9sSD49h8dYitJv5rAPR21lJbAICH1bIYdByWmp3fQOoDyHW"  target="_blank" rel="noopener">松哥git教程</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span>，根据自己实际应用进行删减，并加上了自己的理解和补充，如有侵权，请联系博主本人删除。</p>
</blockquote>
</div><footer class="post-footer"><div class="post-ending ending"><div class="ending__text">------ 本文结束，感谢您的阅读 ------</div></div><div class="post-copyright copyright"><div class="copyright-author"><span class="copyright-author__name">本文作者: </span><span class="copyright-author__value"><a href="https://wxler.gitee.io">wxl</a></span></div><div class="copyright-link"><span class="copyright-link__name">本文链接: </span><span class="copyright-link__value"><a href="https://wxler.gitee.io/2020/06/17/gitUseMethod/">https://wxler.gitee.io/2020/06/17/gitUseMethod/</a></span></div><div class="copyright-notice"><span class="copyright-notice__name">版权声明: </span><span class="copyright-notice__value">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" rel="external nofollow" target="_blank">BY-NC-SA</a> 许可协议。转载请注明出处！</span></div></div><div class="post-tags"><span class="post-tags-item"><span class="post-tags-item__icon"><i class="fas fa-tag"></i></span><a class="post-tags-item__link" href="https://wxler.gitee.io/tags/git/">git</a></span></div><div class="post-share"><div class="social-share" data-sites="qzone, qq, weibo, wechat, douban, linkedin, facebook, twitter, google">分享到：</div></div><nav class="post-paginator paginator"><div class="paginator-prev"><a class="paginator-prev__link" href="/2020/07/15/motto/"><span class="paginator-prev__icon"><i class="fas fa-angle-left"></i></span><span class="paginator-prev__text">奥卡姆剃刀</span></a></div><div class="paginator-next"><a class="paginator-next__link" href="/2020/06/01/hexoCreateAndConfig/"><span class="paginator-prev__text">使用hexo平台从0搭建个人博客</span><span class="paginator-next__icon"><i class="fas fa-angle-right"></i></span></a></div></nav></footer></div></div><div class="comments" id="comments"><div id="valine-container"></div></div></div><div class="sidebar-wrap" id="sidebar-wrap"><aside class="sidebar" id="sidebar"><div class="sidebar-nav"><span class="sidebar-nav-toc current">文章目录</span><span class="sidebar-nav-ov">站点概览</span></div><section class="sidebar-toc"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#git安装和配置"><span class="toc-number">1.</span> <span class="toc-text">
          git安装和配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git工作原理"><span class="toc-number">2.</span> <span class="toc-text">
          git工作原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#基本操作"><span class="toc-number">3.</span> <span class="toc-text">
          基本操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#初始化仓库"><span class="toc-number">3.1.</span> <span class="toc-text">
          初始化仓库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#查看仓库状态"><span class="toc-number">3.2.</span> <span class="toc-text">
          查看仓库状态</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#添加文件到暂存区"><span class="toc-number">3.3.</span> <span class="toc-text">
          添加文件到暂存区</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#提交到本地仓库"><span class="toc-number">3.4.</span> <span class="toc-text">
          提交到本地仓库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#查看更改前后的差异"><span class="toc-number">3.5.</span> <span class="toc-text">
          查看更改前后的差异</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#查看提交历史"><span class="toc-number">3.6.</span> <span class="toc-text">
          查看提交历史</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git撤销修改"><span class="toc-number">4.</span> <span class="toc-text">
          git撤销修改</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#工作区的代码撤销"><span class="toc-number">4.1.</span> <span class="toc-text">
          工作区的代码撤销</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#暂存区的代码撤销"><span class="toc-number">4.2.</span> <span class="toc-text">
          暂存区的代码撤销</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#本地仓库的代码撤销"><span class="toc-number">4.3.</span> <span class="toc-text">
          本地仓库的代码撤销</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git分支管理"><span class="toc-number">5.</span> <span class="toc-text">
          git分支管理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#查看分支"><span class="toc-number">5.1.</span> <span class="toc-text">
          查看分支</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#分支创建和切换"><span class="toc-number">5.2.</span> <span class="toc-text">
          分支创建和切换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#分支合并"><span class="toc-number">5.3.</span> <span class="toc-text">
          分支合并</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#以图表方式查看分支"><span class="toc-number">5.4.</span> <span class="toc-text">
          以图表方式查看分支</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#解决冲突"><span class="toc-number">5.5.</span> <span class="toc-text">
          解决冲突</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#github远程仓库"><span class="toc-number">6.</span> <span class="toc-text">
          github远程仓库</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#关联远程仓库"><span class="toc-number">6.1.</span> <span class="toc-text">
          关联远程仓库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#推送到远程仓库"><span class="toc-number">6.2.</span> <span class="toc-text">
          推送到远程仓库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#从远程仓库获取"><span class="toc-number">6.3.</span> <span class="toc-text">
          从远程仓库获取</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#从远程仓库更新"><span class="toc-number">6.4.</span> <span class="toc-text">
          从远程仓库更新</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git命令大全"><span class="toc-number">7.</span> <span class="toc-text">
          git命令大全</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#遗留问题"><span class="toc-number">8.</span> <span class="toc-text">
          遗留问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考文档"><span class="toc-number">9.</span> <span class="toc-text">
          参考文档</span></a></li></ol></section><!-- ov = overview--><section class="sidebar-ov hide"><div class="sidebar-ov-author"><div class="sidebar-ov-author__avatar"><img class="sidebar-ov-author__avatar_img" src="/assets/myhexo.jpg" alt="avatar"></div><p class="sidebar-ov-author__text">A lifetime of AI</p></div><div class="sidebar-ov-social"><a class="sidebar-ov-social-item" href="https://github.com/wxler" target="_blank" rel="noopener" data-popover="Github" data-popover-pos="up"><span class="sidebar-ov-social-item__icon"><i class="fab fa-github"></i></span></a><a class="sidebar-ov-social-item" href="mailto:wangxiaolei1516@qq.com" target="_blank" rel="noopener" data-popover="邮箱" data-popover-pos="up"><span class="sidebar-ov-social-item__icon"><i class="fa fa-envelope"></i></span></a></div><div class="sidebar-ov-state"><a class="sidebar-ov-state-item sidebar-ov-state-item--posts" href="/archives/"><div class="sidebar-ov-state-item__count">10</div><div class="sidebar-ov-state-item__name">归档</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--categories" href="/categories/"><div class="sidebar-ov-state-item__count">6</div><div class="sidebar-ov-state-item__name">分类</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--tags" href="/tags/"><div class="sidebar-ov-state-item__count">11</div><div class="sidebar-ov-state-item__name">标签</div></a></div><div class="sidebar-ov-cc"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" target="_blank" rel="noopener" data-popover="知识共享许可协议" data-popover-pos="up"><img src="/images/cc-by-nc-sa.svg"></a></div></section></aside></div><div class="clearfix"></div></div></main><footer class="footer" id="footer"><div class="footer-inner"><div><span>Copyright © 2020</span><span class="footer__icon"><i class="fas fa-heart"></i></span><span>wxler. All Rights Reserved.</span></div><div><span>由 <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a> 强力驱动</span><span> v4.2.1</span><span class="footer__devider">|</span><span>主题 - <a href="https://github.com/liuyib/hexo-theme-stun/" title="Stun" target="_blank" rel="noopener">Stun</a></span><span> v2.0.0</span></div><div>托管于 <a href="https://github.com/wxler/" rel="noopener" target="_blank">Github</a></div></div></footer><div class="loading-bar" id="loading-bar"><div class="loading-bar__progress"></div></div><div class="back2top" id="back2top"><span class="back2top__icon"><i class="fas fa-rocket"></i></span></div></div><div class="search-mask"></div><div class="search-popup"><span class="search-close"></span><div class="search-input"><input placeholder="搜索文章（支持多关键词，请用空格分隔）"></div><div class="search-results"></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@v3.4.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.ui.min.js"></script><script src="https://cdn.jsdelivr.net/npm/ribbon.js@latest/dist/ribbon.min.js" size="120" alpha="0.6" zIndex="-1"></script><script src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-rc.2/lazyload.min.js"></script><script src="https://cdn.jsdelivr.net/npm/social-share.js@1.0.16/dist/js/social-share.min.js"></script><script>function initSearch() {
  var isXML = true;
  var search_path = 'search.json';

  if (!search_path) {
    search_path = 'search.xml';
  } else if (/json$/i.test(search_path)) {
    isXML = false;
  }

  var path = '/' + search_path;
  $.ajax({
    url: path,
    dataType: isXML ? 'xml' : 'json',
    async: true,
    success: function (res) {
      var datas = isXML ? $('entry', res).map(function () {
        // 将 XML 转为 JSON
        return {
          title: $('title', this).text(),
          content: $('content', this).text(),
          url: $('url', this).text()
        };
      }).get() : res;
      var $input = $('.search-input input');
      var $result = $('.search-results');
      // 搜索对象（标题、内容）的权重，影响显示顺序
      var WEIGHT = { title: 100, content: 1 };
      var searchPost = function () {
        var searchText = $input.val().toLowerCase().trim();
        // 根据空白字符分隔关键字
        var keywords = searchText.split(/[\s]+/);
        // 搜索结果
        var matchPosts = [];

        // 有多个关键字时，将原文字整个保存下来
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        // 防止未输入字符时搜索
        if (searchText.length > 0) {
          datas.forEach(function (data) {
            var isMatch  = false;
            // 没有标题的文章使用预设的 i18n 变量代替
            var title = (data.title && data.title.trim()) || '[ 文章无标题 ]';
            var titleLower = title && title.toLowerCase();
            // 删除 HTML 标签 和 所有空白字符
            var content = data.content && data.content.replace(/<[^>]+>/g, '');
            var contentLower = content && content.toLowerCase();
            // 删除重复的 /
            var postURL = data.url && decodeURI(data.url).replace(/\/{2,}/g, '/');
            // 标题中匹配到的关键词
            var titleHitSlice = [];
            // 内容中匹配到的关键词
            var contentHitSlice = [];

            keywords.forEach(function (keyword) {
              /**
              * 获取匹配的关键词的索引
              * @param {String} keyword 要匹配的关键字
              * @param {String} text 原文字
              * @param {Boolean} caseSensitive 是否区分大小写
              * @param {Number} weight 匹配对象的权重。权重大的优先显示
              * @return {Array}
              */
              function getIndexByword (word, text, caseSensitive, weight) {
                if (!word || !text) {
                  return [];
                };

                var startIndex = 0; // 每次匹配的开始索引
                var index = -1;     // 匹配到的索引值
                var result = [];    // 匹配结果

                if (!caseSensitive) {
                  word = word.toLowerCase();
                  text = text.toLowerCase();
                }

                while((index = text.indexOf(word, startIndex)) !== -1) {
                  var hasMatch = false;
                  // 索引位置相同的关键词，保留长度较长的
                  titleHitSlice.forEach(function (hit) {
                    if (hit.index === index && hit.word.length < word.length) {
                      hit.word = word;
                      hasMatch = true;
                    }
                  });
                  startIndex = index + word.length;
                  !hasMatch && result.push({ index: index, word: word, weight: weight });
                }
                return result;
              }
              titleHitSlice = titleHitSlice.concat(getIndexByword(keyword, titleLower, false, WEIGHT.title));
              contentHitSlice = contentHitSlice.concat(getIndexByword(keyword, contentLower, false, WEIGHT.content));
            });

            var hitTitle = titleHitSlice.length;
            var hitContent = contentHitSlice.length;

            if (hitTitle > 0 || hitContent > 0) {
              isMatch = true;
            }
            if (isMatch) {
              ;[titleHitSlice, contentHitSlice].forEach(function (hit) {
                // 按照匹配文字的索引的递增顺序排序
                hit.sort(function (left, right) {
                  return left.index - right.index;
                });
              });
              /**
              * 给文本中匹配到的关键词添加标记，从而进行高亮显示
              * @param {String} text 原文本
              * @param {Array} hitSlice 匹配项的索引信息
              * @param {Number} start 开始索引
              * @param {Number} end 结束索引
              * @return {String}
              */
              function highlightKeyword (text, hitSlice, start, end) {
                if (!text || !hitSlice || !hitSlice.length) {
                  return;
                }

                var result = '';
                var startIndex = start;
                var endIndex = end;
                hitSlice.forEach(function (hit) {
                  if (hit.index < startIndex) {
                    return;
                  }

                  var hitWordEnd = hit.index + hit.word.length;
                  result += text.slice(startIndex, hit.index);
                  result += '<b>' + text.slice(hit.index, hitWordEnd) + '</b>';
                  startIndex = hitWordEnd;
                });
                result += text.slice(startIndex, endIndex);
                return result;
              }

              var postData = {};
              // 文章总的搜索权重
              var postWeight = titleHitSlice.length * WEIGHT.title + contentHitSlice.length * WEIGHT.content;
              // 标记匹配关键词后的标题
              var postTitle = highlightKeyword(title, titleHitSlice, 0, title.length) || title;
              // 标记匹配关键词后的内容
              var postContent;
              // 显示内容的长度
              var SHOW_WORD_LENGTH = 200;
              // 命中关键词前的字符显示长度
              var SHOW_WORD_FRONT_LENGTH = 20;
              var SHOW_WORD_END_LENGTH = SHOW_WORD_LENGTH - SHOW_WORD_FRONT_LENGTH;

              // 截取匹配的第一个字符，前后共 200 个字符来显示
              if (contentHitSlice.length > 0) {
                var firstIndex = contentHitSlice[0].index;
                var start = firstIndex > SHOW_WORD_FRONT_LENGTH ? firstIndex - SHOW_WORD_FRONT_LENGTH : 0;
                var end = firstIndex + SHOW_WORD_END_LENGTH;
                postContent = highlightKeyword(content, contentHitSlice, start, end);
              } else { // 未匹配到内容，直接截取前 200 个字符来显示
                postContent = content.slice(0, SHOW_WORD_LENGTH);
              }
              postData.title = postTitle;
              postData.content = postContent;
              postData.url = postURL;
              postData.weight = postWeight;
              matchPosts.push(postData);
            }
          });
        }

        var resultInnerHtml = '';
        if (matchPosts.length) {
          // 按权重递增的顺序排序，使权重大的优先显示
          matchPosts.sort(function (left, right) {
            return right.weight - left.weight;
          });
          resultInnerHtml += '<ul>';
          matchPosts.forEach(function (post) {
            resultInnerHtml += '<li><a class="search-results-title" href="' + post.url + '">';
            resultInnerHtml += post.title;
            resultInnerHtml += '</a><div class="search-results-content">';
            resultInnerHtml += post.content;
            resultInnerHtml += '</div></li>';
          });
          resultInnerHtml += '</ul>';
        } else {
          resultInnerHtml += '<div class="search-results-none"><i class="far fa-meh"></i></div>';
        }
        $result.html(resultInnerHtml);
      };
      $input.on('input', searchPost);
      $input.on('keyup', function (e) {
        if (e.keyCode === Stun.utils.codeToKeyCode('Enter')) {
          searchPost();
        }
      });
    }
  });
}

function closeSearch () {
  $('body').css({ overflow: 'auto' });
  $('.search-popup').css({ display: 'none' });
  $('.search-mask').css({ display: 'none' });
}

window.addEventListener('DOMContentLoaded', function () {
  Stun.utils.pjaxReloadLocalSearch = function () {
    $('.header-nav-search').on('click', function (e) {
      e.stopPropagation();
      $('body').css('overflow', 'hidden');
      $('.search-popup')
        .velocity('stop')
        .velocity('transition.expandIn', {
          duration: 300,
          complete: function () {
            $('.search-popup input').focus();
          }
        });
      $('.search-mask')
        .velocity('stop')
        .velocity('transition.fadeIn', {
          duration: 300
        });

      initSearch();
    });
    $('.search-mask, .search-close').on('click', function () {
      closeSearch();
    });
    $(document).on('keydown', function (e) {
      // Escape <=> 27
      if (e.keyCode === Stun.utils.codeToKeyCode('Escape')) {
        closeSearch();
      }
    });
  };

  Stun.utils.pjaxReloadLocalSearch();
}, false);</script><script src="https://cdn.jsdelivr.net/npm/pjax@latest/pjax.min.js"></script><script>window.addEventListener('DOMContentLoaded', function () {
  var pjax = new Pjax({"selectors":["head title","#main",".pjax-reload"],"history":true,"scrollTo":false,"scrollRestoration":false,"cacheBust":false,"debug":false,"currentUrlFullReload":false,"timeout":0});
  // 加载进度条的计时器
  var loadingTimer = null;

  // 重置页面 Y 方向上的滚动偏移量
  document.addEventListener('pjax:send', function () {
    $('.header-nav-menu').removeClass('show');
    if (CONFIG.pjax && CONFIG.pjax.avoidBanner) {
      $('html').velocity('scroll', {
        duration: 500,
        offset: $('#header').height(),
        easing: 'easeInOutCubic'
      });
    }

    var loadingBarWidth = 20;
    var MAX_LOADING_WIDTH = 95;

    $('.loading-bar').addClass('loading');
    $('.loading-bar__progress').css('width', loadingBarWidth + '%');
    clearInterval(loadingTimer);
    loadingTimer = setInterval(function () {
      loadingBarWidth += 3;
      if (loadingBarWidth > MAX_LOADING_WIDTH) {
        loadingBarWidth = MAX_LOADING_WIDTH;
      }
      $('.loading-bar__progress').css('width', loadingBarWidth + '%');
    }, 500);
  }, false);

  window.addEventListener('pjax:complete', function () {
    clearInterval(loadingTimer);
    $('.loading-bar__progress').css('width', '100%');
    $('.loading-bar').removeClass('loading');
    setTimeout(function () {
      $('.loading-bar__progress').css('width', '0');
    }, 400);
    $('link[rel=prefetch], script[data-pjax-rm]').each(function () {
      $(this).remove();
    });
    $('script[data-pjax], #pjax-reload script').each(function () {
      $(this).parent().append($(this).remove());
    });

    if (Stun.utils.pjaxReloadBoot) {
      Stun.utils.pjaxReloadBoot();
    }
    if (Stun.utils.pjaxReloadScroll) {
      Stun.utils.pjaxReloadScroll();
    }
    if (Stun.utils.pjaxReloadSidebar) {
      Stun.utils.pjaxReloadSidebar();
    }
    if (false) {
      if (Stun.utils.pjaxReloadHeader) {
        Stun.utils.pjaxReloadHeader();
      }
      if (Stun.utils.pjaxReloadScrollIcon) {
        Stun.utils.pjaxReloadScrollIcon();
      }
      if (Stun.utils.pjaxReloadLocalSearch) {
        Stun.utils.pjaxReloadLocalSearch();
      }
    }
  }, false);
}, false);</script><div id="pjax-reload"><link href="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/katex.min.css" rel="stylesheet" type="text/css"><link href="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/contrib/copy-tex.css" rel="stylesheet" type="text/css"><script src="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/contrib/copy-tex.min.js"></script></div><script src="https://cdn.jsdelivr.net/npm/leancloud-storage@latest/dist/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js"></script><script data-pjax="">function loadValine () {
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var guest_info = 'nick,mail';

  guest_info = guest_info.split(',').filter(function(item) {
    return GUEST_INFO.indexOf(item) > -1;
  });
  new Valine({
    el: '#valine-container',
    appId: 'kBUfBo302Sl5ViCNcWef6wYT-gzGzoHsz',
    appKey: 'hq4rU6YND5ziczBa2PLLUBiM',
    notify: true,
    verify: false,
    placeholder: '有什么需要和我说的，请填写昵称与邮箱(邮箱不会公开显示)，点击评论吧(支持匿名评论)！',
    avatar: 'mp',
    meta: guest_info,
    pageSize: '15' || 10,
    visitor: false,
    recordIP: false,
    lang: '' || 'zh-cn',
    path: window.location.pathname
  });
}

if (true) {
  loadValine();
} else {
  window.addEventListener('DOMContentLoaded', loadValine, false);
}</script><script src="/js/utils.js?v=2.0.0"></script><script src="/js/stun-boot.js?v=2.0.0"></script><script src="/js/scroll.js?v=2.0.0"></script><script src="/js/header.js?v=2.0.0"></script><script src="/js/sidebar.js?v=2.0.0"></script></body></html>